package com.test.test11.task;

import android.os.AsyncTask;
import android.util.Log;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.test11.SharedConstants;
import com.test.test11.WebURL;
import com.test.test11.entity.ResponseResult;
import com.test.test11.entity.User;
import com.test.test11.http.AfterRequest;
import com.test.test11.http.HttpClient;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录请求
 */

public class UserLoginTask extends AsyncTask<String, Void, String> {

    private static final String TAG = "USER_LOGIN";

    private AfterRequest afterLogin;

    /**
     * 构造函数
     * @param afterLogin
     */
    public UserLoginTask(AfterRequest afterLogin) {
        this.afterLogin = afterLogin;
    }

    /**
     * 用户登录后台执行代码
     * @param strings 用户名和密码，第一个参数表示用户名，第二个参数表示密码，第三个表示手机号
     * @return
     */
    @Override
    protected String doInBackground(String... strings) {
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(strings[2])) {
            params.put("phoneNumber", strings[2]);
        }
        if(StringUtils.isNotBlank(strings[0])){
            params.put("username", strings[0]);
        }
        params.put("pwd", strings[1]);
        try{
            String result = HttpClient.getInstance().post(WebURL.USER_LOGIN, params);
            return result;
        } catch (IOException e) {
            Log.e(TAG, "登录请求发生异常");
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(String s) {
        if(StringUtils.isBlank(s)){
            afterLogin.failure(-1, "网络连接错误，请检查网络");
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            ResponseResult result = mapper.readValue(s, ResponseResult.class);
            User user = mapper.readValue(mapper.writeValueAsString(result.getObject()), User.class);
            SharedConstants.updateUser(user);
            if(result.getCode()==0){
                afterLogin.success();
            }else{
                afterLogin.failure(result.getCode(), result.getMsg());
            }
        } catch (IOException e) {
            // 此处不应该出现异常，出现异常那说明程序设计的有问题
            Log.e(TAG, "登录请求结果解析错误："+s);
            e.printStackTrace();
        }
    }
}
